package com.vm.activity;

import java.util.ArrayList;
import org.json.JSONObject;
import com.vm.commons.CurrentUser;
import com.vm.commons.VMConst;
import com.vm.model.UserInfo;
import com.vm.utils.ApkUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月23日 下午2:53:07]
 * @Version: [v1.0]
 * 
 */
@SuppressWarnings("deprecation")
@SuppressLint("HandlerLeak")
public class ShareActivity extends Activity {
	private RequestQueue mQueue;
	private Tencent mTencent;
	private static final String APP_ID = "222222";
	ImageView imgbtn_search_back;
	RelativeLayout rlayout_invCode_none;
	TextView tv_invCode;
	LinearLayout llayout_share1;
	LinearLayout llayout_share2;
	private IWXAPI wxApi;
	Button btn_copy_invite_code;
	RelativeLayout rlayout_invCode_true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.invite_install_layout);
		mQueue = MyVolley.getRequestQueue();
		wxApi = WXAPIFactory.createWXAPI(this, "");
		wxApi.registerApp("");
		btn_copy_invite_code = (Button) findViewById(R.id.btn_copy_invite_code);
		llayout_share1 = (LinearLayout) findViewById(R.id.llayout_share1);
		llayout_share2 = (LinearLayout) findViewById(R.id.llayout_share2);
		rlayout_invCode_true = (RelativeLayout) findViewById(R.id.rlayout_invCode_true);
		rlayout_invCode_none = (RelativeLayout) findViewById(R.id.rlayout_invCode_none);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		btn_copy_invite_code.setOnClickListener(copy_listener);
		final Context ctxContext = this.getApplicationContext();
		mTencent = Tencent.createInstance(APP_ID, ctxContext);
		mHandler = new Handler();

		tv_invCode = (TextView) findViewById(R.id.tv_invCode);
		if (CurrentUser.PHONNE != null) {
			String url = VMConst.REQUEST_URL + "getByPhone?phone="
					+ CurrentUser.PHONNE;
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url,
					null, new Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject arg0) {
							// TODO Auto-generated method stub
							UserInfo userInfo = JsonUtils.jsonToBean(arg0,
									UserInfo.class);
							if (userInfo.getPromoterName() != null) {
								CurrentUser.INVCODE = userInfo
										.getPromoterName();
								rlayout_invCode_none.setVisibility(View.GONE);
								rlayout_invCode_true
										.setVisibility(View.VISIBLE);
								tv_invCode.setText(CurrentUser.INVCODE);
								llayout_share1.setVisibility(View.VISIBLE);
								llayout_share2.setVisibility(View.VISIBLE);
							} else {
								rlayout_invCode_none
										.setVisibility(View.VISIBLE);
								// tv_invCode.setText("您还没有邀请码,点我去设置一个吧!");
								// tv_invCode
								// .setOnClickListener(setInvCodeListener);
								rlayout_invCode_true.setVisibility(View.GONE);
								rlayout_invCode_none
										.setOnClickListener(setInvCodeListener);
								llayout_share1.setVisibility(View.GONE);
								llayout_share2.setVisibility(View.GONE);
							}
						}

					}, null);
			mQueue.add(jsonObjectRequest);
		} else {
			// tv_invCode.setText("您还没有邀请码,点我去设置一个吧!");
			// tv_invCode
			// .setOnClickListener(setInvCodeListener);
			rlayout_invCode_true.setVisibility(View.GONE);
			rlayout_invCode_none.setVisibility(View.VISIBLE);
			llayout_share1.setVisibility(View.GONE);
			llayout_share2.setVisibility(View.GONE);
		}
	}

	OnClickListener copy_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (CurrentUser.INVCODE != null) {
				copy(CurrentUser.INVCODE);
				Toast.makeText(getApplicationContext(), "已复制到剪贴板",
						Toast.LENGTH_LONG).show();
			}
		}

	};
	OnClickListener setInvCodeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			if (CurrentUser.USERID != null) {
				intent = new Intent(ShareActivity.this,
						SetInvCodeActivity.class);
				startActivity(intent);
			} else {
				intent = new Intent(ShareActivity.this, LoginActivity.class);
				Toast.makeText(getApplicationContext(), "请先登录",
						Toast.LENGTH_LONG).show();
				startActivity(intent);
			}

		}
	};

	@Override
	protected void onResume() {

		if (CurrentUser.INVCODE != null) {
			rlayout_invCode_none.setVisibility(View.GONE);
			rlayout_invCode_true.setVisibility(View.VISIBLE);
			tv_invCode.setText(CurrentUser.INVCODE);
			tv_invCode.setEnabled(false);
			llayout_share1.setVisibility(View.VISIBLE);
			llayout_share2.setVisibility(View.VISIBLE);
		} else {
			llayout_share1.setVisibility(View.GONE);
			llayout_share2.setVisibility(View.GONE);
			rlayout_invCode_none.setVisibility(View.VISIBLE);
			rlayout_invCode_true.setVisibility(View.GONE);
			rlayout_invCode_none.setOnClickListener(setInvCodeListener);
		}
		TextView tv_qq = (TextView) findViewById(R.id.tv_qq);
		TextView tv_weixin = (TextView) findViewById(R.id.tv_weixin);
		TextView tv_weixin1 = (TextView) findViewById(R.id.tv_weixin1);
		TextView tv_frends = (TextView) findViewById(R.id.tv_frends);
		TextView tv_frends1 = (TextView) findViewById(R.id.tv_frends1);
		TextView tv_qq1 = (TextView) findViewById(R.id.tv_qq1);
		TextView tv_kongjian = (TextView) findViewById(R.id.tv_kongjian);
		TextView tv_kongjian1 = (TextView) findViewById(R.id.tv_kongjian1);
		TextView tv_weibo = (TextView) findViewById(R.id.tv_weibo);
		TextView tv_weibo1 = (TextView) findViewById(R.id.tv_weibo1);
		TextView tv_xinxi = (TextView) findViewById(R.id.tv_xinxi);
		tv_qq.setOnClickListener(shareListener);
		tv_weixin.setOnClickListener(shareListener);
		tv_weixin1.setOnClickListener(shareListener);
		tv_frends.setOnClickListener(shareListener);
		tv_frends1.setOnClickListener(shareListener);
		tv_qq1.setOnClickListener(shareListener);
		tv_kongjian.setOnClickListener(shareListener);
		tv_kongjian1.setOnClickListener(shareListener);
		tv_weibo.setOnClickListener(shareListener);
		tv_weibo1.setOnClickListener(shareListener);
		tv_xinxi.setOnClickListener(shareListener);
		if (!wxApi.isWXAppInstalled()) {
			tv_weixin.setVisibility(View.GONE);
			tv_weixin1.setVisibility(View.VISIBLE);
			tv_frends.setVisibility(View.GONE);
			tv_frends1.setVisibility(View.VISIBLE);
		} else {
			tv_weixin1.setVisibility(View.GONE);
			tv_weixin.setVisibility(View.VISIBLE);
			tv_frends1.setVisibility(View.GONE);
			tv_frends.setVisibility(View.VISIBLE);
		}
		if (!ApkUtils
				.isAppInstalled("com.tencent.mobileqq", ShareActivity.this)) {
			tv_qq.setVisibility(View.GONE);
			tv_qq1.setVisibility(View.VISIBLE);
		} else {
			tv_qq.setVisibility(View.VISIBLE);
			tv_qq1.setVisibility(View.GONE);
		}
		if (!ApkUtils.isAppInstalled("com.qzone", ShareActivity.this)) {
			tv_kongjian.setVisibility(View.GONE);
			tv_kongjian1.setVisibility(View.VISIBLE);
		} else {
			tv_kongjian.setVisibility(View.VISIBLE);
			tv_kongjian1.setVisibility(View.GONE);
		}
		if (!ApkUtils.isAppInstalled("com.sina.weibo", ShareActivity.this)) {
			tv_weibo.setVisibility(View.GONE);
			tv_weibo1.setVisibility(View.VISIBLE);
		} else {
			tv_weibo.setVisibility(View.VISIBLE);
			tv_weibo1.setVisibility(View.GONE);
		}
		super.onResume();

	}

	public void copy(String content) {
		ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		cmb.setText(content);
	}

	OnClickListener shareListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(ShareActivity.this, DetailActivity.class);
			switch (v.getId()) {
			case R.id.tv_weixin:
				wechatShare(0);
				break;
			case R.id.tv_weixin1:
				intent.putExtra("softId",
						"402417be-7cb3-4238-8122-5f4ab095305c");
				startActivity(intent);
				break;
			case R.id.tv_frends:
				wechatShare(1);
				break;
			case R.id.tv_frends1:

				intent.putExtra("softId",
						"402417be-7cb3-4238-8122-5f4ab095305c");
				startActivity(intent);
				break;
			case R.id.tv_qq:
				ShareToQQ();
				break;
			case R.id.tv_qq1:
				intent.putExtra("softId",
						"57df6b0a-edc9-487c-b141-1309ef797988");
				startActivity(intent);
				break;
			case R.id.tv_kongjian:
				shareToQzone();
				break;
			case R.id.tv_kongjian1:
				intent.putExtra("softId",
						"1a77163f-6bf1-4d62-91e1-0569c78f5360");
				startActivity(intent);
				break;
			case R.id.tv_weibo:

				break;
			case R.id.tv_weibo1:
				intent.putExtra("softId",
						"185a0193-ff1c-4e4d-aa6e-660251b7eb03");
				startActivity(intent);
				break;
			case R.id.tv_xinxi:
				shareToMessage();
				break;
			default:
				break;
			}
		}

	};
	// private void onClickShareToQQ2() {
	// final Activity context = ShareActivity.this;
	// new GetShareToQQParamsDialog(context,
	// new GetShareToQQParamsDialog.ShareToQQParamsListener() {
	//
	// @Override
	// public void onComplete(Bundle params) {
	//
	// // 两种方式使用分享:1主线程，2子线程
	// /*
	// * 主线程 doShareToQQ(params);
	// */
	// /* 子线程 */
	// shareParams = params;
	// Thread thread = new Thread(shareThread);
	// thread.start();
	//
	// }
	// }).show();
	//
	// }

	// private void onClickShareToQQ() {
	// Bundle b = getShareBundle();
	// if (b != null) {
	// shareParams = b;
	// Thread thread = new Thread(shareThread);
	// thread.start();
	// }
	// }

	// private Bundle getShareBundle() {
	//
	// Bundle bundle = new Bundle();
	// bundle.putString("title", "万维通云应用手机App");
	// bundle.putString("imageUrl",
	// "http://www.91pcapp.com/site/qrcode/20153/19/com.example.vmclient.png");
	// bundle.putString(
	// "targetUrl",
	// "http://www.91pcapp.com/downloadApk?softId=96f480a8-6911-46f0-a92f-11ea4a42304e");
	// bundle.putString("summary", "万维通云应用手机App,一个专注于App推广的平台");
	// bundle.putString("site", "2222");
	// bundle.putString("appName", "万维通云应用手机App");
	// return bundle;
	// }

	Bundle shareParams = null;

	Handler shareHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};

	// 线程类，该类使用匿名内部类的方式进行声明
	Runnable shareThread = new Runnable() {

		public void run() {
			doShareToQQ(shareParams);
			Message msg = shareHandler.obtainMessage();

			// 将Message对象加入到消息队列当中
			shareHandler.sendMessage(msg);

		}
	};

	private void doShareToQQ(Bundle params) {
		mTencent.shareToQQ(ShareActivity.this, params, new BaseUiListener() {
			protected void doComplete(JSONObject values) {
				showResult("shareToQQ:", "onComplete");
			}

			@Override
			public void onError(UiError e) {
				showResult("shareToQQ:", "onError code:" + e.errorCode
						+ ", msg:" + e.errorMessage + ", detail:"
						+ e.errorDetail);
			}

			@Override
			public void onCancel() {
				showResult("shareToQQ", "onCancel");
			}
		});
	}

	private class BaseUiListener implements IUiListener {

		@SuppressWarnings("unused")
		public void onComplete(JSONObject response) {
			// mBaseMessageText.setText("onComplete:");
			// mMessageText.setText(response.toString());
			doComplete(response);
		}

		protected void doComplete(JSONObject values) {

		}

		@Override
		public void onError(UiError e) {
			showResult("onError:", "code:" + e.errorCode + ", msg:"
					+ e.errorMessage + ", detail:" + e.errorDetail);
		}

		@Override
		public void onCancel() {
			showResult("onCancel", "");
		}

		@Override
		public void onComplete(Object arg0) {
			// TODO Auto-generated method stub

		}
	}

	private Handler mHandler;

	private void showResult(final String base, final String msg) {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
			}
		});
	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

	private void wechatShare(int flag) {
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = "http://img.91pcapp.com/wwtapk.apk";
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "万维通市场";
		msg.description = "我的邀请码:" + CurrentUser.INVCODE + ",填写邀请码注册可获得100积分哦";
		Bitmap thumb = BitmapFactory.decodeResource(getResources(),
				R.drawable.logo2);
		msg.setThumbImage(thumb);

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = String.valueOf(System.currentTimeMillis());
		req.message = msg;
		req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
				: SendMessageToWX.Req.WXSceneTimeline;
		wxApi.sendReq(req);
	}

	private void ShareToQQ() {
		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, "万维通市场");
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "我的邀请码:"
				+ CurrentUser.INVCODE + ",填写邀请码注册可获得100积分哦");
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
				"http://img.91pcapp.com/wwtapk.apk");
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
				"http://img.91pcapp.com/wwtlogo.png");
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "万维通市场");
		params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
		mTencent.shareToQQ(ShareActivity.this, params, new BaseUiListener());
	}

	private void shareToQzone() {
		final Bundle params = new Bundle();
		ArrayList<String> image = new ArrayList<String>();
		image.add("http://img.91pcapp.com/wwtlogo.png");
		params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
				QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "万维通市场");// 必填
		params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "我的邀请码:"
				+ CurrentUser.INVCODE + ",填写邀请码注册可获得100积分哦");// 选填
		params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,
				"http://img.91pcapp.com/wwtapk.apk");// 必填
		params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, image);
		mTencent.shareToQzone(ShareActivity.this, params, new BaseUiListener());
	}

	private void shareToMessage() {
		String msg = "http://img.91pcapp.com/wwtapk.apk   " + ",我的邀请码"
				+ CurrentUser.INVCODE + ",填写邀请码注册可获得100积分哦";
		String number = "";
		Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
		sendIntent.setData(Uri.parse("smsto:" + number));
		sendIntent.putExtra("sms_body", msg);
		startActivity(sendIntent);
	}
}
